package site.kexing.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import site.kexing.config.MybaitsUtils;
import site.kexing.mapper.EquipmentMapper;
import site.kexing.pojo.Equipment;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
public class EquipmentController {
    private static  final Logger logger = LoggerFactory.getLogger(ProductController.class);
    // 项目根路径下的目录  -- SpringBoot static 目录相当于是根路径下（SpringBoot 默认）
    public final static String UPLOAD_PATH_PREFIX = "static/equipmentImg/";
    @Autowired
    private EquipmentMapper equipmentMapper;

    //查询所有产品
    @RequestMapping("/selectallequipment")
    public String selectAllEquipment(@RequestParam(defaultValue = "1") Integer currentPage, Model model){
        PageHelper.startPage(currentPage, 7);
        List<Equipment> equipment = equipmentMapper.selectAllEquipment();
        PageInfo<Equipment> pageInfo = new PageInfo<Equipment>(equipment,7);
        model.addAttribute("pageInfo",pageInfo);
        return "equipment";
    }

    //根据id查询信息
    @RequestMapping("/selectequipmentbyid")
    public String selectEquipmentByID(Integer id, Model model){
        Equipment equipment = equipmentMapper.selectEquipmentByID(id);
        model.addAttribute("equipment",equipment);
        return "equipmentUpdate";
    }

    @RequestMapping("/updateequipment")
    public String updateEquipment(@ModelAttribute("equipment") Equipment equipment){
        equipment.setUpdate_time(new Date());
        int i = equipmentMapper.updateEquipment(equipment);
        System.out.println(equipment);
        System.out.println(i);
        return "redirect:/selectallequipment";
    }

    @RequestMapping("/deleteequipmentbyid")
    public String deleteEquipmentByID(Integer id){
        int i = equipmentMapper.deleteEquipment(id);
        return "redirect:/selectallequipment";
    }

    @RequestMapping("/insertequipment")
    public String insertEquipment(@RequestParam("equipment_img_urls") MultipartFile uploadFile, HttpServletRequest request, Equipment equipment) throws IOException {
//        //构建文件上传所要保存的"文件夹路径"--这里是相对路径，保存到项目根路径的文件夹下
//        String realPath = new String("src/main/resources/" + UPLOAD_PATH_PREFIX);
//        logger.info("-----------上传文件保存的路径【"+ realPath +"】-----------");
//        //存放上传文件的文件夹
//        File file = new File(realPath );
//        logger.info("-----------存放上传文件的文件夹【"+ file +"】-----------");
//        logger.info("-----------输出文件夹绝对路径 -- 这里的绝对路径是相当于当前项目的路径而不是“容器”路径【"+ file.getAbsolutePath() +"】-----------");
//        if(!file.isDirectory()){
//            //递归生成文件夹
//            file.mkdirs();
//        }
//        //获取原始的名字  original:最初的，起始的  方法是得到原来的文件名在客户机的文件系统名称
//        String oldName = uploadFile.getOriginalFilename();
//        logger.info("-----------文件原始的名字【"+ oldName +"】-----------");
//        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."),oldName.length());
//        logger.info("-----------文件要保存后的新名字【"+ newName +"】-----------");
//        try {
//            //构建真实的文件路径
//            File newFile = new File(file.getAbsolutePath() + File.separator + newName);
//            //转存文件到指定路径，如果文件名重复的话，将会覆盖掉之前的文件,这里是把文件上传到 “绝对路径”
//            uploadFile.transferTo(newFile);
//            String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/equipmentImg/" + newName;
//            logger.info("-----------【"+ filePath +"】-----------");
//            equipment.setEquipment_img_url(filePath);
//            equipment.setEquipment_seq(MybaitsUtils.getUUID());
//            equipment.setCreate_time(new Date());
//            equipment.setUpdate_time(new Date());
//            System.out.println(equipment);
//            int i = equipmentMapper.insertEquipment(equipment);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return "redirect:/selectallequipment";

        if(!uploadFile.isEmpty()){
            String path = ResourceUtils.getURL("classpath:").getPath()+"static/productImg";
            String realPath = path.replace('/', '\\').substring(1,path.length());
            System.out.println(realPath);

            final String fileName = MybaitsUtils.getUUID()+uploadFile.getOriginalFilename();

            String contentType = uploadFile.getContentType();
            if("image/jpeg".equals(contentType) || "image/jpg".equals(contentType) ){
                File file = new File(realPath,fileName);

                uploadFile.transferTo(file);
                System.out.println("图片上传成功!");
                String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/productImg/" + fileName;

                equipment.setEquipment_img_url(filePath);
                equipment.setEquipment_seq(MybaitsUtils.getUUID());
                equipment.setCreate_time(new Date());
                equipment.setUpdate_time(new Date());
                equipmentMapper.insertEquipment(equipment);
                return "redirect:/selectallequipment";
            } else {
                System.out.println("上传失败！");
                return "redirect:/productupdate";
            }
        } else {
            System.out.println("上传失败！");
            return "redirect:/productupdate";
        }
    }

    @RequestMapping("/selectequipmentbyname")
    public String selectEquipmentByName(@RequestParam(defaultValue = "1") Integer currentPage,String equipment_name,Model model){
        PageHelper.startPage(currentPage, 7);
        List<Equipment> equipment = equipmentMapper.selectEquipmentByName(equipment_name);
        System.out.println(equipment);
        PageInfo<Equipment> pageInfo = new PageInfo<Equipment>(equipment,7);
        model.addAttribute("pageInfo",pageInfo);
        return "equipment";
    }
}
